package com.gxa.service.activities.impl;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R.ResponseData;
import com.gxa.mapper.activities.ActivitiesMapper;
import com.gxa.pojo.Activity;
import com.gxa.pojo.ActivityContent;
import com.gxa.service.activities.Activities;
import com.gxa.service.employee.impl.PhotoUploadServiceImpl;
import com.gxa.utils.FileUtil;
import com.gxa.utils.RandomUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ActivitiesImpl implements Activities {

    @Autowired
    private ActivitiesMapper activitiesMapper;

    private static final Logger logger = LoggerFactory.getLogger(ActivitiesImpl.class);

    // 设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "UrROlnoMH8xRLIEumZiTUJsRIESlRm8MCFZ5WWcU";
    String SECRET_KEY = "YOZcn7DcJD_3q793XwEVc-RHv2klrBWo7QXYIa4G";
    // 要上传的空间
    String bucketname = "renshiguanli";

    // 密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    // 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
    Configuration cfg = new Configuration(Zone.zone2());
    // ...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);

    // 测试域名，只有30天有效期
    private static String QINIU_IMAGE_DOMAIN = "http://ra2kk7kmp.hn-bkt.clouddn.com/";

    // 简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    /*
    查询所有活动
     */
    @Override
    public ResponseData selectActivity(int currentPage, int pageSize, String activityName) {
        if (activityName==null){
            activityName="";
        }
        int count = activitiesMapper.selectCount(activityName);

        int index = (currentPage-1)*pageSize;
        List<Activity> activityList = activitiesMapper.selectActivity(pageSize, index, activityName);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("查询所有活动成功");
        responseData.setData(activityList);
        responseData.setTotal(count);
        return responseData;
    }

    /*
    查询活动数据总数
     */
    @Override
    public int selectCount(String activityName) {
        return activitiesMapper.selectCount(activityName);
    }

    @Override
    public int selectContentCount(String theme) {
        return activitiesMapper.selectContentCount(theme);
    }

    /*
    修改活动名称和图片地址
     */
    @Override
    public ResponseData updateActivity(String activityName, MultipartFile file,int id) {
        ResponseData responseData = new ResponseData();
        if(file.isEmpty()) {
            responseData.setCode(500);
            responseData.setMsg("上传失败!!!");
            return responseData;
        }
        String activityPhoto = "";
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }
            //生成六位随机数作为文件名
            String fileName = RandomUtils.generateString(6).toString().replaceAll("-","")+"."+fileExt;
//          String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                activityPhoto = QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("上传失败:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("上传请求失败:" + e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        activitiesMapper.updateActivity(activityName,activityPhoto,id);
        responseData.setCode(200);
        responseData.setMsg("修改活动成功");
        return responseData;
    }

    /*
    基于id删除活动
     */
    @Override
    public ResponseData delete(int id) {
        int delete = activitiesMapper.delete(id);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("删除活动成功");
        return responseData;
    }
    /*
    添加活动
     */
    @Override
    public ResponseData insertActivity(String activityName,  MultipartFile file) {
        ResponseData responseData = new ResponseData();
        if(file.isEmpty()) {
            responseData.setCode(500);
            responseData.setMsg("上传失败!!!");
            return responseData;
        }
        String activityPhoto = "";
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return null;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            // 判断是否是合法的文件后缀
            if (!FileUtil.isFileAllowed(fileExt)) {
                return null;
            }
            //生成六位随机数作为文件名
            String fileName = RandomUtils.generateString(6).toString().replaceAll("-","")+"."+fileExt;
//          String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getUpToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                activityPhoto = QINIU_IMAGE_DOMAIN + JSONObject.parseObject(res.bodyString()).get("key");
            } else {
                logger.error("上传失败:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            logger.error("上传请求失败:" + e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        int i = activitiesMapper.insertActivity(activityName, activityPhoto);
        responseData.setCode(200);
        responseData.setMsg("添加活动成功");
        return responseData;
    }

    /*
    查询活动内容
     */
    @Override
    public ResponseData selectByTheme(Integer currentPage, Integer pageSize, String theme) {
        int count = activitiesMapper.selectContentCount(theme);
        int index = (currentPage-1)*pageSize;
        List<ActivityContent>  activityContentList=activitiesMapper.selectByTheme(pageSize,index,theme);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("查询活动内容成功");
        responseData.setData(activityContentList);
        responseData.setTotal(count);
        return responseData;
    }

    /*
    新真活动内容
     */
    @Override
    public ResponseData insertById(int id, String theme, String time, String content) {
        int insert=activitiesMapper.insertById(id,theme,time,content);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("新增活动内容成功");

        return responseData;

    }

    /*
    基于活动内容id删除
     */
    @Override
    public ResponseData deleteById(int id) {
        int delete =activitiesMapper.deleteById(id);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("删除活动内容成功");
        return responseData;
    }

    /*
    修改活动内容
     */
    @Override
    public ResponseData updateContent(int id,String theme, String time, String content) {
        int updateContent=activitiesMapper.updateContent(id,theme,time,content);
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("修改活动内容成功");
        return responseData;
    }

//    @Override
//    public ResponseData updatePhoto(MultipartFile file) {
//        return null;
//    }

}
